package com.bite.common.security.handler;

import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.security.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理
 * @author 均先生
 */
@Slf4j
@RestController
public class GlobalExceptionHandler {
    /**
     * 请求方式不支持
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求",requestURI,e.getMethod());
        return R.fail(ResultCode.ERROR);
    }

    /**
     * 拦截运行时异常
     * @param e
     * @param request
     * @return
     */

    @ExceptionHandler(RuntimeException.class)
    public R<?> handleRuntimeException(RuntimeException e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生运行时异常。",requestURI,e);
        return R.fail(ResultCode.ERROR);
    }

    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生异常。",requestURI,e);
        return R.fail(ResultCode.ERROR);
    }

    @ExceptionHandler(ServiceException.class)
    public R<?> handleException(ServiceException e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        ResultCode resultCode = e.getResultCode();
        log.error("请求地址'{}',发生业务异常:'{}'.",requestURI,resultCode.getMsg(),e);
        return R.fail(resultCode);
    }
}
